package com.lyu.xiaolvshu.note.biz.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;

@Configuration
public class ThreadPoolConfig {

    @Bean(name = "taskExecutor")
    public Executor taskExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        //核心线程数10
        executor.setCorePoolSize(10);
        //最大线程数50
        executor.setMaxPoolSize(50);
        //队列容量200
        executor.setQueueCapacity(200);
        //线程活跃时间 30s
        executor.setKeepAliveSeconds(30);
        //线程名前缀
        executor.setThreadNamePrefix("NoteExecutor-");
        //拒绝策略:由调用线程处理
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        //等待所有任务结束后再关闭线程池
        executor.setWaitForTasksToCompleteOnShutdown(true);
        //等待线程关闭时间,如果超过这个时间还有任务没完成就强制销毁
        executor.setAwaitTerminationSeconds(60);

        executor.initialize();
        return executor;
    }
}
